<template>
  <div class="guild-notice-manage">
    <h2>公会公告管理</h2>
    <el-table :data="notices" style="width: 100%" border>
      <el-table-column prop="id" label="ID" align="center"></el-table-column>
      <el-table-column prop="guildId" label="公会ID" align="center"></el-table-column>
      <el-table-column prop="title" label="公告标题" align="center"></el-table-column>
      <el-table-column prop="content" label="公告内容" align="center">
        <template #default="scope">
          <el-tooltip content="查看详情" effect="dark">
            <div class="content-ellipsis" @click="showContentDetail(scope.row.content)">{{ scope.row.content }}</div>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column prop="publishTime" label="发布时间" align="center">
        <template #default="scope">
          {{ formatDate(scope.row.publishTime) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template #default="scope">
          <el-button size="mini" @click="showEditDialog(scope.row)">编辑</el-button>
          <el-button size="mini" type="danger" @click="handleDelete(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-button type="primary" @click="showAddDialog">发布新公告</el-button>
    <!-- 新增分页组件 -->
    <el-pagination
        @size-change="handlePageSizeChange"
        @current-change="handleCurrentPageChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalRecords"
    />

    <!-- 发布新公告对话框 -->
    <el-dialog title="发布新公告" v-model="addDialogVisible" width="30%">
      <el-form :model="newNotice" :rules="rules" ref="addFormRef">
        <el-form-item label="公会ID" prop="guildId">
          <el-input v-model="newNotice.guildId"></el-input>
        </el-form-item>
        <el-form-item label="公告标题" prop="title">
          <el-input v-model="newNotice.title"></el-input>
        </el-form-item>
        <el-form-item label="公告内容" prop="content">
          <el-input type="textarea" v-model="newNotice.content" rows="4"></el-input>
        </el-form-item>
        <el-form-item label="发布时间" prop="publishTime">
          <el-date-picker
              v-model="newNotice.publishTime"
              type="datetime"
              placeholder="选择发布时间"
              value-format="YYYY-MM-DD HH:mm:ss"
          ></el-date-picker>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="publishNotice">确 定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 编辑公告对话框 -->
    <el-dialog title="编辑公告" v-model="editDialogVisible" width="30%">
      <el-form :model="currentNotice" :rules="rules" ref="editFormRef">
        <el-form-item label="公会ID" prop="guildId">
          <el-input v-model="currentNotice.guildId"></el-input>
        </el-form-item>
        <el-form-item label="公告标题" prop="title">
          <el-input v-model="currentNotice.title"></el-input>
        </el-form-item>
        <el-form-item label="公告内容" prop="content">
          <el-input type="textarea" v-model="currentNotice.content" rows="4"></el-input>
        </el-form-item>
        <el-form-item label="发布时间" prop="publishTime">
          <el-date-picker
              v-model="currentNotice.publishTime"
              type="datetime"
              placeholder="选择发布时间"
              value-format="YYYY-MM-DD HH:mm:ss"
          ></el-date-picker>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="updateNotice">确 定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 公告内容详情对话框 -->
    <el-dialog title="公告详情" v-model="contentDetailVisible" width="40%">
      <div class="notice-content">{{ contentDetail }}</div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="contentDetailVisible = false">关 闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import request from "@/utils/request";
import dayjs from "dayjs";

const notices = ref([]);
const newNotice = ref({
  guildId: "",
  title: "",
  content: "",
  publishTime: dayjs().format("YYYY-MM-DD HH:mm:ss")
});
const currentNotice = ref({});
const addDialogVisible = ref(false);
const editDialogVisible = ref(false);
const contentDetailVisible = ref(false);
const contentDetail = ref("");

const addFormRef = ref(null);
const editFormRef = ref(null);

const rules = {
  guildId: [{ required: true, message: "请输入公会ID", trigger: "blur" }],
  title: [{ required: true, message: "请输入公告标题", trigger: "blur" }],
  content: [{ required: true, message: "请输入公告内容", trigger: "blur" }],
  publishTime: [{ required: true, message: "请选择发布时间", trigger: "change" }]
};

const formatDate = (dateString) => {
  if (!dateString) return "";
  return dayjs(dateString).format("YYYY-MM-DD HH:mm:ss");
};

const showContentDetail = (content) => {
  contentDetail.value = content;
  contentDetailVisible.value = true;
};

// 新增分页相关变量
const currentPage = ref(1);
const pageSize = ref(10);
const totalRecords = ref(0);

const getNotices = async () => {
  try {
    const res = await request.get("/guild/notices/all", {
      params: {
        page: currentPage.value,
        pageSize: pageSize.value
      }
    });
    if (res && res.data && res.data.records && Array.isArray(res.data.records)) {
      notices.value = res.data.records;
      totalRecords.value = res.data.total;
    } else {
      ElMessage.error("获取公会公告列表失败，数据格式不正确");
    }
  } catch (error) {
    console.error("获取公会公告列表出错:", error);
    ElMessage.error("网络请求失败，请检查网络连接");
  }
};

onMounted(() => {
  getNotices();
});

const showAddDialog = () => {
  newNotice.value = {
    guildId: "",
    title: "",
    content: "",
    publishTime: dayjs().format("YYYY-MM-DD HH:mm:ss")
  };
  addDialogVisible.value = true;
};

const publishNotice = async () => {
  try {
    await addFormRef.value.validate();
    const res = await request.post("/guild/notice", newNotice.value);
    if (res) {
      ElMessage.success("发布公告成功");
      await getNotices();
      addDialogVisible.value = false;
    } else {
      ElMessage.error("发布公告失败");
    }
  } catch (error) {
    console.error("发布公告出错:", error);
    ElMessage.error("网络请求失败，请检查网络连接");
  }
};

const showEditDialog = (row) => {
  currentNotice.value = {
    ...row,
    publishTime: row.publishTime? formatDate(row.publishTime) : null
  };
  editDialogVisible.value = true;
};

const updateNotice = async () => {
  try {
    await editFormRef.value.validate();
    const res = await request.put("/guild/notice", currentNotice.value);
    if (res) {
      ElMessage.success("更新公告成功");
      await getNotices();
      editDialogVisible.value = false;
    } else {
      ElMessage.error("更新公告失败");
    }
  } catch (error) {
    console.error("更新公告出错:", error);
    ElMessage.error("网络请求失败，请检查网络连接");
  }
};

const handleDelete = async (id) => {
  ElMessageBox.confirm("确定要删除此公告吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(async () => {
    try {
      const res = await request.delete(`/guild/notice/${id}`);
      if (res) {
        ElMessage.success("删除公告成功");
        await getNotices();
      } else {
        ElMessage.error("删除公告失败");
      }
    } catch (error) {
      console.error("删除公告出错:", error);
      ElMessage.error("网络请求失败，请检查网络连接");
    }
  });
};

// 每页数量改变时的处理
const handlePageSizeChange = (newPageSize) => {
  pageSize.value = newPageSize;
  currentPage.value = 1;
  getNotices();
};

// 当前页码改变时的处理
const handleCurrentPageChange = (newPage) => {
  currentPage.value = newPage;
  getNotices();
};
</script>

<style scoped>
.guild-notice-manage {
  padding: 20px;
}

.content-ellipsis {
  max-width: 200px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  cursor: pointer;
}

.notice-content {
  white-space: pre-wrap;
  line-height: 1.8;
  padding: 10px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  background-color: #fafafa;
}
</style>